import axios from 'axios';
import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { showToast } from '@nutui/nutui';
import { useUserStore } from '@/store/modules/user';
import router from '@/router';

export interface HttpResponse<T = unknown> {
  code?: string | number;
  msg?: string;
  data?: T;
  rows?: unknown;
  total?: number;
}

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api';
const TOKEN_KEY = import.meta.env.VITE_TOKEN_KEY || '';

// 防止401死循环的标志位
let isHandling401 = false;

const service: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  withCredentials: false,
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (TOKEN_KEY) {
      const token = localStorage.getItem(TOKEN_KEY);
      if (token) {
        config.headers = {
          ...config.headers,
          Authorization: `Bearer ${token}`,
        };
      }
    }
    return config;
  },
  (error: AxiosError) => Promise.reject(error),
);

service.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data || {};
    const code = typeof res.code === 'number' ? res.code : Number(res.code || 200);
    if (code !== 200) {
      const message = res.msg || '请求失败';
      
      // 401 未授权，需要登录
      if (code === 401 && !isHandling401) {
        isHandling401 = true;
        const userStore = useUserStore();
        // 直接清除本地登录信息，不调用logout接口（避免再次触发401）
        userStore.setToken('');
        userStore.setInfo(null);
        // 跳转到登录页
        router.push({
          path: '/login',
          replace: true,
        }).finally(() => {
          // 延迟重置标志位，确保跳转完成
          setTimeout(() => {
            isHandling401 = false;
          }, 1000);
        });
      } else if (code !== 401) {
        showToast.text(message);
      }
      
      return Promise.reject(new Error(message));
    }
    return res;
  },
  (error: AxiosError) => {
    // 处理 HTTP 状态码 401
    if (error.response?.status === 401 && !isHandling401) {
      isHandling401 = true;
      const userStore = useUserStore();
      // 直接清除本地登录信息，不调用logout接口（避免再次触发401）
      userStore.setToken('');
      userStore.setInfo(null);
      // 跳转到登录页
      router.push({
        path: '/login',
        replace: true,
      }).finally(() => {
        // 延迟重置标志位，确保跳转完成
        setTimeout(() => {
          isHandling401 = false;
        }, 1000);
      });
      return Promise.reject(new Error('请登录...'));
    }
    
    const message = error.message || '网络异常';
    if (!isHandling401) {
      showToast.text(message);
    }
    return Promise.reject(error);
  },
);

export const http = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<HttpResponse<T>> {
    return service.get(url, config);
  },

  post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<HttpResponse<T>> {
    return service.post(url, data, config);
  },

  put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<HttpResponse<T>> {
    return service.put(url, data, config);
  },

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<HttpResponse<T>> {
    return service.delete(url, config);
  },
};

export default service;
